%%%-------------------------------------------------------------------
%%% @author chenlong
%%% @copyright (C) 2019, <COMPANY>
%%% @doc
%%% 玩家进程相关 工具函数
%%% @end
%%% Created : 18. 三月 2019 16:37
%%%-------------------------------------------------------------------
-module(role_lib).
-author("chenlong").

-include("common.hrl").

%% API
-export([sendToMyClient/1,sendToClient/2, broadcastToClient/2,broadcastToClient/3,
	sendToPlayerServer/2,
	getRolePublic/1, getRoleOnline/1]).

%%========================EXPORTED FUNCTION===============================
sendToMyClient(Msg) ->
	case get(?SEND_TO_SOCKET_FUN) of
		Fun when is_function(Fun, 1) ->
			sendMsgToClient(Fun,Msg);
		_ ->
			?ERR("no SEND_TO_SOCKET_FUN"),
			ok
	end.
sendToClient(RoleID, Msg) ->
	#role_online{sendToSocketFun = SendFun}=getRoleOnline(RoleID),
	sendMsgToClient(SendFun,Msg).

broadcastToClient(EtsRoomOrPlayerIDList,Msg)->
	broadcastToClient(EtsRoomOrPlayerIDList,Msg,0).
broadcastToClient(#ets_room{playerList = PlayerList},Msg,ExPlayerID) ->
	broadcastToClient([MemberID||#room_player{playerID = MemberID}<-PlayerList],Msg,ExPlayerID);
broadcastToClient(PlayerIDList, Msg,ExPlayerID) ->
	Fun = fun(PlayerID) ->
		try
			case PlayerID == ExPlayerID of
				?TRUE -> ok;
				_ -> case getRoleOnline(PlayerID) of
							 #role_online{sendToSocketFun = SendFun} -> sendMsgToClient(SendFun,Msg);
							 _ -> ok
						 end
			end
		catch
			_ -> ok
		end
	      end,
	lists:foreach(Fun, PlayerIDList).

sendToPlayerServer(RoleID, Msg) ->
	#role_online{rolePID = RolePID}=getRoleOnline(RoleID),
	RolePID ! Msg.

getRolePublic(RoleID) ->
	case ets:lookup(?ETS_ROLE_PUBLIC, RoleID) of
		[RolePublic] ->
			role_public_server ! {refPublic,RoleID},
			RolePublic;
		_ ->
			role_public_server:loadRolePublic(RoleID)
	end.
getRoleOnline(RoleID) ->
	case ets:lookup(?ETS_ROLE_ONLINE,RoleID) of
		[RoleOnline] -> RoleOnline;
		_ -> none
	end.

%%========================LOCAL FUNCTION===============================
sendMsgToClient(Fun, Msg) ->
	?DEBUG("send to client Msg=~p",[Msg]),
	spawn(fun() -> Fun(proto:encode(Msg)) end).